﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jumpton.SFA.Server.Entity;
using Jumpton.Data;
using Jumpton.Persistent;
using System.Data;

namespace Jumpton.SFA.Server.BusinessRule.System
{
    public class DomainManager : BusinessLogic
    {

        #region 判断域是否存在
        /// <summary>
        /// 判断域是否存在
        /// </summary>
        /// <param name="code">域代码</param>
        /// <returns></returns>
        public static bool IsExitsDomain(string code)
        {
            return ObjectRow.Load(typeof(DOMAINS), "this.CODE='" + code + "'") != null;

        }

        /// <summary>
        /// 递归获取从当前域开始的所有子域,包括未无效的
        /// </summary>
        /// <param name="DomainID"></param>
        /// <returns></returns>
        public DataTable GetDomainsWithRecursion(decimal DomainID)
        {
            string sql = "SELECT * FROM [DOMAINS]";
            return SqlData.OpenSql(sql).Tables[0];
            //return GetDomainsWithRecursion(DomainID, true);
        }

        /// <summary>
        /// 递归获取从当前域开始的所有子域,包括未无效的
        /// </summary>
        /// <param name="DomainID"></param>
        /// <returns></returns>
        public DataTable GetDomainsObject()
        {
            string sql = @"SELECT D.ID,D.CODE,SYS_NAME,D.CREATE_TIME,D.LAST_UPDATER,U.CODE CODE2,D.LAST_UPDATE_TIME,
            SYSTEM_ADDITIONAL_INFO1 SYSTEMADDITIONALINFO1, SYSTEM_ADDITIONAL_INFO2 SYSTEMADDITIONALINFO2,
            SYSTEM_ADDITIONAL_INFO3 SYSTEMADDITIONALINFO3,
        D.ACTIVE,U2.CODE ADMINCODE  
        FROM [DOMAINS] D LEFT JOIN USERS U ON D.LAST_UPDATER = U.ID 
        LEFT JOIN USERS U2 ON U2.RIGHTS = 3 AND U2.DOMAIN_ID = D.ID";
            return SqlData.OpenSql(sql).Tables[0];
            //return GetDomainsWithRecursion(DomainID, true);
        }

        /// <summary>
        /// 递归获取从当前域开始的所有子域,包括未无效的
        /// </summary>
        /// <param name="DomainID"></param>
        /// <returns></returns>
        public ObjectRow GetDomainsObject(decimal DomainID)
        {
            return (TAXES)ObjectRow.Load(typeof(TAXES), string.Format("a.ID={0}", DomainID));
        }

        /// <summary>
        /// 递归获取从当前域开始的所有子域
        /// </summary>
        /// <param name="DomainID">父域ID</param>
        /// <param name="IncludeDisable">是否包含置为无效的域</param>
        /// <returns></returns>
        public DataTable GetDomainsWithRecursion(decimal DomainID, Boolean IncludeDisable)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format(@"with ColumnCTE ( id,parentdomainid,code,sysname,sys_id_no,level)
            as
            (
            select id, parentdomainid,code,sys_name as 'sysname',sys_id_no,0 as level from domains where id = {0}", DomainID));
            if (!IncludeDisable)
                sb.Append(" and isvalid=1");
            sb.Append(" union all select tt.id,tt.parentdomainid,tt.code,tt.sys_name as 'sysname',tt.sys_id_no,level+1 from domains tt join ColumnCTE cte on tt.parentdomainid = cte.id");
            if (!IncludeDisable)
                sb.Append(" and tt.isvalid=1");
            sb.Append(") select * from ColumnCTE");
            return SqlData.OpenSql(sb.ToString()).Tables[0];

        }
        #endregion

        #region 创建一个域和复制域数据
        /// <summary>
        /// 新建一个域
        /// </summary>
        /// <param name="code">域代码</param>
        /// <param name="sysName">系统名称</param>
        /// <param name="sysID">系统ID</param>
        /// <returns></returns>
        public int CrateDomain(DOMAINS domain, string createName)
        {

            try
            {
                return SqlData.ExecuteSP("SP_CREATE_DOMAIN", domain.CODE, domain.SYSNAME,domain.LAST_UPDATER, domain.SYSTEMADDITIONALINFO1,
                    domain.SYSTEMADDITIONALINFO2, domain.SYSTEMADDITIONALINFO3, domain.SYSTEMADDITIONALINFO4,
                    domain.SYSTEMADDITIONALINFO5);
            }
            catch (Exception err)
            {
                return -1;
            }
        }

        /// <summary>
        /// 复制一个域数据至另一个域(非基础数据)
        /// </summary>
        /// <param name="OLD_Domain_ID">域代码</param>
        /// <param name="NEW_Domain_ID">系统名称</param>
        /// <param name="User_Code">系统ID</param>
        /// <returns>是否成功,-1为失败</returns>
        public int CrateDomain(int OLD_Domain_ID, int NEW_Domain_ID, string User_Code)
        {
            try
            {
                return SqlData.ExecuteSP("SP_COPY_DOMAIN_DATA", OLD_Domain_ID, NEW_Domain_ID, User_Code);
            }
            catch (Exception err)
            {
                return -1;
            }
        }
        #endregion

        public DOMAINS LoadByCode(string code, decimal domainID)
        {
            return (DOMAINS)ObjectRow.Load(typeof(DOMAINS), string.Format("this.CODE='{0}' and this.ID<>'{1}'", code, domainID));
        }



        public decimal Save(DOMAINS route)
        {
            if (route != null)
            {
                try
                {

                    if (this.LoadByCode(route.CODE, route.ID) != null)
                    {
                        throw new Exception("代码已存在");
                    }

                    route.Save();
                }
                catch (Exception err)
                {
                    message = err.Message; throw err;
                }
                return route.ID;
            }

            return 0;
        }

        public ObjectTable GetDomainByCode(string code)
        {
            string str = string.Empty;
            if (!string.IsNullOrEmpty(code))
            {
                str = "this.CODE like '%" + code + "%'";
            }
            return new ObjectTable(typeof(DOMAINS), str, "this.LAST_UPDATE_TIME desc");
        }

        public ObjectTable Load()
        {
            return new ObjectTable(typeof(DOMAINS), "");
        }

        public DOMAINS Load(decimal domainID)
        {
            return (DOMAINS)ObjectRow.Load(typeof(DOMAINS), "this.ID='" + domainID + "'");
        }

        public static void CopyMeasureManagement(decimal oldDomain, decimal newDomain)
        {
            SqlData.ExecuteSP("usp_CopyMEASURE_PROFILES", oldDomain, newDomain);
        }
    }
}
